/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.format;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.oslef.csv.CSVWriter;
import org.oslef.csv.RowWriter;

public final class Writer {

	private RowWriter loanWriter;
	private RowWriter historyWriter;
	private RowWriter installmentWriter;

	public Writer(Schema schema, File oslefDir) throws IOException {
		{
			File file = new File(oslefDir.getAbsoluteFile(), "loans.csv");
			java.io.Writer w = new FileWriter(file);
			loanWriter = new RowWriter(schema.loan(), new CSVWriter(w));
			loanWriter.writeHeader();
		}
		{
			File file = new File(oslefDir.getAbsoluteFile(), "installments.csv");
			java.io.Writer w = new FileWriter(file);
			installmentWriter = new RowWriter(schema.installmentPlan(), new CSVWriter(w));
			installmentWriter.writeHeader();
		}
		{
			File file = new File(oslefDir.getAbsoluteFile(), "history.csv");
			java.io.Writer w = new FileWriter(file);
			historyWriter = new RowWriter(schema.history(), new CSVWriter(w));
			historyWriter.writeHeader();
		}
	}
	
	public void write(Loan loan) throws IOException {
		
		String loanId = loan.loan.get(Constants.LOAN_ID);
		
		if (StringUtil.isEmpty(loanId)) {
			System.out.println("asdf");
		}

		write(loan.loan, loanWriter, loanId);
		
		for (Record i : loan.installments) {
			write(i, installmentWriter, loanId);
		}
		
		for (Record h : loan.history) {
			write(h, historyWriter, loanId);
		}
	}
	
	private void write(Record r, RowWriter w, String loanId) throws IOException {
		
		w.clear();
		
		w.put(Constants.LOAN_ID, loanId);
		
		for (String key : r.keys()) {
			w.put(key, r.get(key));
		}
		
		w.write();
	}
	
	public void close() throws IOException {
		loanWriter.close();
		historyWriter.close();
		installmentWriter.close();
	}
}
